<template>
    <div>
        <!-- 文件选择 -->
        <el-dialog title="文件选择" :visible.sync="cloudDialogVisible" :width="cloudWidth" :beforeClose="beforeClose"
            :destroy-on-close="true" class="cloud" v-dialogDrag :key="list.id" v-if="cloudDialogVisible">
            <cloudPreview @cancel="cancel" @selectFile="selectFile" v-on="$listeners" v-bind="$attrs" :title="list.code"
                ref="cloudPreview" :key="loading" />
        </el-dialog>
        <!-- 预览 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :width="previewWidth" class="preview" v-dialogDrag
            v-if="dialogVisible">
            <!-- <div class="left_dialog" v-if="list.type === 'multifile'">
                <i class="el-icon-caret-left"></i>
            </div>
            <div class="right_dialog" @click="next" v-if="list.type === 'multifile'">
                <i class="el-icon-caret-right"></i>
            </div> -->
            <components is="filePreview" :list="dataList" v-if="dialogVisible"></components>
            <div slot="footer"></div>
        </el-dialog>
        <div class="main">
            <div class="main_title">{{ list.title }}</div>
            <div class="main_content">
                <el-input v-model="dataFileName" :disabled="true">
                </el-input>
                <el-popover placement="bottom" width="260" trigger="click">
                    <div style="display: flex;justify-content: space-around;">
                        <div class="hover" @click="monitorUploadData(list.code)">
                            <i class="el-icon-monitor" style="transform: scale(1.5);margin-bottom: 5px;"></i>
                            <span>本地文件</span>
                        </div>
                        <div class="hover" @click="openCloudDialog(list.code)">
                            <i class="el-icon-cloudy" style="transform: scale(1.5);margin-bottom: 5px;"></i>
                            <span>云端文件</span>
                        </div>

                        <div class="hover" @click="giveExample(['demo'])" v-if="list.default2 !== 'multifile'">
                            <i class="el-icon-document" style="transform: scale(1.5);margin-bottom: 5px;"></i>
                            <span>示例文件</span>
                        </div>
                    </div>

                    <div class="progress" v-if="all && percentage">
                        <div>
                            <span>{{ current }}</span>
                            <span>/{{ all }}</span>
                        </div>
                        <div>
                            <el-progress :percentage="Number(percentage)" status="success" color="#999"></el-progress>
                        </div>
                    </div>
                    <div style="font-size: 12px;color: #999;text-align: center;margin-top: 10px;">
                        <span>支持文件类型:txt、tsv、csv、gbk</span>
                        <span style="cursor: pointer;color: #2a82e4;" @click="downloadSample(list.code)">(下载示例)</span>
                    </div>
                    <el-button slot="reference" icon="el-icon-upload2" type="primary" plain
                        @click="title = list.code">上传</el-button>
                </el-popover>
                <el-button icon="el-icon-document" type="primary" plain @click="beforePreview(list.code, fileId)"
                    v-show="list.default2 !== 'multifile'">预览</el-button>
            </div>
            <input type="file" :id="`file-input-common${list.code}`" style="display: none;"
                @change="fileUpload($event, list.code)" :multiple="list.default2 === 'multifile' ? true : false">
        </div>
    </div>
</template>

<script>
import { uploadFilesRequest, downloadSampleRequest, previewDataRequest, getFileGroupRequest, uploadCloudPictureDataFileRequest } from '@/api/tools'
import { getToken } from '@/utils/auth';
import filePreview from './filePreview.vue'
import cloudPreview from './cloudPreview.vue'
export default {
    name: 'GenescloudUiDataFile',
    components: { filePreview, cloudPreview },
    props: {
        list: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            //预览
            dialogVisible: false,
            dialogTitle: null,
            previewWidth: '800px',
            //云端文件
            cloudDialogVisible: false,
            cloudWidth: '750px',
            loading: 0, //控制云端文件刷新
            //预览数据
            dataList: {},
            title: '',
            ws: null,
            sessionId: null,
            uploadId: null,
            //当前进度
            current: 0,
            //文件总大小
            all: '',
            dataFileName: null,
            currentAll: 0,
            //进度
            percentage: 0,
            //上传的文件
            file: null,
            currentNumber: 0,
            //文件ID
            fileId: 'demo',
            fileSize: null,
            //组件code
            cloudPictureCode: null,
        };
    },
    async created() {
        this.fileId = this.$attrs.option.analysisForm[this.list.code + 'FileId#']
        this.dataFileName = this.$attrs.option.analysisForm[this.list.code + 'FileName#']
        this.$resizeDialog(800, this.previewWidth)
        this.$resizeDialog(750, this.cloudWidth)
        this.cloudPictureCode = this.$router.history.current.name
        if (getToken()) {
            this.ws = await this.$webSocket('file')
            this.ws.onopen = () => {
                // console.log('打开连接');
            },
                this.ws.onmessage = (evt) => {
                    if (JSON.parse(evt.data).file_session_id) {
                        this.sessionId = JSON.parse(evt.data).file_session_id
                    }
                    if (JSON.parse(evt.data).uploadId == this.uploadId) {
                        this.current = JSON.parse(evt.data).uploadByteCount
                        if (this.current) {
                            this.current = this.$allSizeDeal(this.fileSize, this.current)
                            this.percentage = (this.current / this.all.split('.')[0]) * 100 || 0
                        }
                    }
                },
                this.ws.onconsole = () => {
                    // console.log('断开');
                },
                this.ws.onerror = (value) => {
                    // console.log(value, '错误！');
                }
        }
    },
    beforeDestroy() {
        this.$unResizeDialog()
    },
    methods: {
        //本地上传
        monitorUploadData(id) {
            if (this.all) return this.$message.error('文件正在上传中，请勿频繁点击！')
            document.querySelector(`#file-input-common${id}`).click()
        },
        //文件上传
        async fileUpload(e, type) {
            let res
            if (this.list.default2 === "multifile") {
                let files = e.target.files;
                let formData = new FormData();
                let name = ''
                for (let i = 0; i < files.length; i++) {
                    formData.append("file" + i, files[i]);
                    name += ' ' + files[i].name
                }
                this.uploadId = Date.now()
                res = await uploadCloudPictureDataFileRequest(
                    this.cloudPictureCode,
                    this.title,
                    this.sessionId,
                    this.uploadId,
                    formData)
                if (res.code !== 200) return this.$message.error(res.message)
                this.$message({
                    showClose: true,
                    message: '文件上传成功！',
                    type: 'success'
                })
                this.dataFileName = name
                // this.$emit('updateFiles', { type: type, id: res.data.recordId })
            } else {
                this.file = e.target.files[0];
                if (!this.file) return
                // const tsv = this.file.name.split('.')[1] !== 'tsv'
                // const txt = this.file.name.split('.')[1] !== 'txt'
                // const csv = this.file.name.split('.')[1] !== 'csv'
                // const xls = this.file.name.split('.')[1] !== 'xls'
                // const xlsx = this.file.name.split('.')[1] !== 'xlsx'
                // if (tsv && txt && csv && xls && xlsx) return this.$message.error('暂不支持该文件格式！')
                this.fileSize = this.file.size
                this.all = this.$size2Str(this.file.size)
                this.uploadId = Date.now()
                const formData = new FormData();
                formData.append('file', this.file);
                res = await uploadCloudPictureDataFileRequest(
                    this.cloudPictureCode,
                    this.title,
                    this.sessionId,
                    this.uploadId,
                    formData)
                if (res.code == 200) {
                    this.$message({
                        showClose: true,
                        message: '文件上传成功！',
                        type: 'success'
                    })
                    this.fileId = res.data.recordId
                    if (this.list.code === 'data') this.$emit('fileUpload', res.data.recordId)
                    this.all = ''
                    this.current = 0
                    this.percentageGroup = 0
                    this.percentage = 0
                    //input显示文本名
                    this.dataFileName = this.file.name
                } else {
                    this.$message.error(res.message)
                    this.all = false
                }
            }
            this.$emit('changeFile', res.data.recordId, this.list.code)
            //允许上传同一个文件
            e.srcElement.value = ""
            // }
        },
        next() {
            this.beforePreview(this.list.code, '1714575689816076289')
            this.$forceUpdate();
        },
        async beforePreview(code, fileId) {
            // 'demo' ,"1714575689816076289"
            previewDataRequest({
                cloudPictureCode: this.cloudPictureCode,
                fileId,
                uploadFileType: code
            }).then(res => {
                if (res.code !== 200) return this.$message.error(res.message)
                //文件名
                this.dialogTitle = this.list.title
                this.dialogVisible = true
                const data = res.data.dataList
                console.log(data, 'data');
                this.dataList = data
                // this.dataList.title = Object.keys(data[0])
                // this.dataList.content = data
            })
        },
        //下载示例
        async downloadSample(value) {
            const res = await downloadSampleRequest(this.cloudPictureCode, value)
            var export_blob = new Blob([res]);
            var save_link = document.createElement("a");
            save_link.href = window.URL.createObjectURL(export_blob);
            save_link.download = 'data.txt';
            var ev = document.createEvent("MouseEvents");
            ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(ev);
        },
        async giveExample(id) {
            //修改开始绘图状态
            this.$emit('changeFile', id, this.list.code)
            if (this.list.code === 'data') this.$emit('fileUpload', id)
        },
        //云端文件
        beforeClose() {
            this.$refs.cloudPreview.cancel()
            this.loading++
        },
        cancel(value) {
            this.cloudDialogVisible = value
        },
        //选中文件
        async selectFile(value) {
            if (value.length > 1 && this.list.default2 === 'multifile') {
                let id = []
                let title = ''
                value.forEach(item => {
                    id.push(item.id)
                    title += (' ' + item.text)
                })
                this.dataFileName = title
                this.$emit('changeFile', id, this.list.code)
                if (this.list.code === 'data') this.$emit('fileUpload', id)
                this.cloudDialogVisible = false
            } else if (value.length > 1 && this.list.default2 !== 'multifile') {
                return this.$message.error('数据文件请选择单个生成！')
            } else {
                const { id, text } = value[0]
                this.dataFileName = text
                this.fileId = id
                this.cloudDialogVisible = false
                this.$emit('changeFile', [id], this.list.code)
                if (this.list.code === 'data') this.$emit('fileUpload', [id])
            }
        },
        //云端文件
        async openCloudDialog(val) {
            this.loading++
            this.cloudDialogVisible = true
        },
    },
};
</script>

<style lang="scss" scoped>
.main {
    // margin-top: 15px;
    transform: translateX(-100px);

    .main_title {
        font-size: 14px;
        color: #606266;
        font-weight: 700;
    }

    .main_content {
        padding: 15px 0;
        display: flex;

        ::v-deep .el-button--primary.is-plain,
        ::v-deep .el-input.is-disabled .el-input__inner {
            transform: scale(0.8);
        }
    }

    .progress {
        text-align: center;
        // display: flex;
        // flex-direction: column;
        // align-items: center;
    }
}

.hover {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #999;
    cursor: pointer;
    // border-right: 1px solid #ccc;
    padding-right: 13px;

    &:last-child {
        border-right: 0;
        padding-right: 0;
    }

    &:hover {
        color: #2a82e4 !important;
    }
}

.preview {
    ::v-deep .el-dialog {
        overflow: visible !important;
    }

    // dialog样式
    ::v-deep .el-dialog__header {
        padding: 10px 0 !important;
        background: #fff;
        text-align: center;
        border-bottom: 1px solid #e9e9e9;

        .el-dialog__title {
            color: #777 !important;
            font-weight: 400;
        }
    }

    ::v-deep .el-dialog__body {
        position: relative;
        // margin: 0 25px 0;
        margin: 15px;
        padding: 0;
        border: 1px solid #e9e9e9;
        border-radius: 7px;

        // border-top: 1px solid #ccc;
        //   border-bottom: 1px solid #ccc;
        // position: relative;
        // padding: 0 0 65px;
        // height: 450px;
        .left_dialog,
        .right_dialog {
            cursor: pointer;
            z-index: 99999;
            background-color: #fff;
            width: 40px;
            height: 40px;
            border-radius: 20px;
            text-align: center;
            line-height: 40px;
            font-size: 25px;
        }

        .left_dialog {
            position: absolute;
            left: -90px;
            top: 40%;
        }

        .right_dialog {
            position: absolute;
            right: -90px;
            top: 40%;
        }
    }

    ::v-deep .el-dialog__footer {
        // margin: 25px;
        // height: 15px;
        // background-color: red;
        margin: 0;
        padding: 0;
        height: 1px;

    }
}

.cloud {
    ::v-deep .el-dialog__header {
        font-weight: 700;
        text-align: center;
    }

    ::v-deep .el-dialog__body {
        padding: 0 20px 35px;
    }

    ::v-deep .el-dialog__footer {
        height: 1px;
    }
}
</style>